package com.dt.zbcy.provider.core.shiro;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.Serializable;


public class MySessionManager extends DefaultWebSessionManager {  
  
	
    private final static Logger logger = LoggerFactory.getLogger(MySessionManager.class);
    
	private final String X_AUTH_TOKEN = "x-auth-token"; 
  
    private static final String REFERENCED_SESSION_ID_SOURCE = "Stateless request";  
  
    public MySessionManager() {  
        super();  
    }

    /**
     * 前后端分离的项目，通过ajax发送请求，所以不能像http请求那样通过cookie进行会话验证，需要用请求头的方式，故要重写shiro原生在cookie中回去sessionid的方式
     * @param request
     * @param response
     * @return
     */
    @Override  
    protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
    	String id = WebUtils.toHttp(request).getHeader(X_AUTH_TOKEN);
    	logger.info("MySessionManager.getSessionId:请求头：[{}]",id);
        //如果请求头中有 X_AUTH_TOKEN 则其值为sessionId  
        if (!StringUtils.isEmpty(id)&&!("undefined").equals(id)) {
        	logger.info("MySessionManager.getSessionId:请求头会话验证");
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, REFERENCED_SESSION_ID_SOURCE);  
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, id);  
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);  
            return id;  
        } else { 
        	logger.info("MySessionManager.getSessionId:cookie会话验证");
            //否则按默认规则从cookie取sessionId  
            return super.getSessionId(request, response);  
        }  
    }	
    
    
}  